//this just initialises the media element stuff
$(document).ready(init);

function init()
{	
	loadContent(0);
};

function initMedia()
{
	$('audio,video').mediaelementplayer();
}

function initSidebar(){
	var $window = $(window)
	
	//TOC
	$('.bs-docs-sidenav').affix
	(
		{
			offset: 
			{
				top: function () { return $window.width() <= 980 ? 290 : 210 },
				bottom: 270
			}
		}
	)
}

function loadContent(index){
	$.ajax({
	
		type: "GET",
		url: 'content.xml',
		dataType: "html",
		success: function(data) {
		
			//clear out existing content
			$('#mainContent').empty();
			$('#toc').empty();
			$('#nav').empty();
		
			//add all the pages to the pages menu: this links bak to the same page
			$(data).find('page').each( function(index, value){
				$('#nav').append('<li class=""><a href="javascript:loadContent(' + index + ')">' + $(this).attr('title') + '</a></li>');
			});
		
			//which page is this from the document?
			var page = $(data).children().eq(index);

		
			//set the main page title and subtitle			
			$('#pageTitle').text( page.attr('title') );
			$('#pageSubTitle').text( page.attr('subtitle') );
			
			//create the sections
			page.find('section').each( function(index, value){
			
				//add a TOC entry
				$('#toc').append('<li><a href="#section' + index + '">' + $(this).attr('title') + '</a></li>');
				
				//add the section header
				var section = $('<section id="section' + index + '"><div class="page-header"><h1>' + $(this).attr('title') + '</h1></div></section>');
				
				//add the section contents
				section.append( $(this).html() );

				//add the section to the document
				$('#mainContent').append(section);
								
			});
			
			//finish initialising the piece now we hae the content loaded
			initMedia();
			initSidebar();
			
			twttr.widgets.load();
			FB.XFBML.parse(); 
			
			$('section').append('<p><br><a class="btn btn-mini pull-right" href="#">Top</a></p>');
		}
	})
}